/**
 * Ajax请求封装
 * @param {Object} conf
 */
export const Arequest = (conf) => {
  // ajax操作
  let url = conf.url,
    data = conf.data,
    senData = [], // 封装后的数据
    async = conf.async !== undefined ? conf.async : true, // ture为异步请求
    type = conf.type || "get", // 默认请求方式get
    dataType = conf.dataType || "json",
    contenType = conf.contenType || "application/x-www-form-urlencoded",
    success = conf.success,
    error = conf.error,
    isForm = conf.isForm || false, // 是否formdata
    header = conf.header || {}, // 头部信息
    xhr = ""; // 创建ajax引擎对象
  if (data == null) {
    senData = "";
  } else if (typeof data === "object" && !isForm) {
    // 如果data是对象，转换为字符串
    for (var k in data) {
      senData.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
    }
    senData = senData.join("&");
  } else {
    senData = data;
  }
  try {
    xhr = new ActiveXObject("microsoft.xmlhttp"); // IE内核系列浏览器
  } catch (e1) {
    try {
      xhr = new XMLHttpRequest(); // 非IE内核浏览器
    } catch (e2) {
      if (error != null) {
        error("不支持ajax请求");
      }
    }
  }
  xhr.open(type, type !== "get" ? url : url + "?" + senData, async);
  if (type !== "get" && !isForm) {
    xhr.setRequestHeader("content-type", contenType);
  }
  for (var h in header) {
    xhr.setRequestHeader(h, header[h]);
  }
  xhr.send(type !== "get" ? senData : null);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        if (dataType === "json" && success != null) {
          let res = "";
          try {
            res = eval("(" + xhr.responseText + ")");
          } catch (e) {
            console.log(e);
          }
          success(res); // 将json字符串转换为js对象
        }
      } else {
        if (error != null) {
          error("通讯失败!" + xhr.status);
        }
      }
    }
  };
};

/**
 * 封装fetch请求
 * @param {String} url
 * @param {Object} setting
 * @returns
 */
export const Frequest = function (url, setting) {
  // fetch请求的封装
  let opts = {
    // 设置参数的初始值
    method: (setting.method || "GET").toUpperCase(), // 请求方式
    headers: setting.headers || {}, // 请求头设置
    credentials: setting.credentials || true, // 设置cookie是否一起发送
    body: setting.body || {},
    mode: setting.mode || "no-cors", // 可以设置 cors, no-cors, same-origin
    redirect: setting.redirect || "follow", // follow, error, manual
    cache: setting.cache || "default", // 设置 cache 模式 (default, reload, no-cache)
  };
  let dataType = setting.dataType || "json"; // 解析方式
  let data = setting.data || ""; // 参数
  let paramsFormat = function (obj) {
    // 参数格式
    var str = "";
    for (var i in obj) {
      str += `${i}=${obj[i]}&`;
    }
    return str.split("").slice(0, -1).join("");
  };

  if (opts.method === "GET") {
    url = url + (data ? `?${paramsFormat(data)}` : "");
  } else {
    setting.body = data || {};
  }
  return new Promise((resolve, reject) => {
    fetch(url, opts)
      .then(async (res) => {
        let data =
          dataType === "text"
            ? await res.text()
            : dataType === "blob"
            ? await res.blob()
            : await res.json();
        resolve(data);
      })
      .catch((e) => {
        reject(e);
      });
  });
};
